<?php
namespace app\api\logic;

use app\common\logic\Base;
use Filipac\Ip;
use jwt\Jwt;
use think\facade\App;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Env;
use think\facade\Hook;
use think\facade\Log;
use think\facade\Request;

class General extends  Base {
    
    
    /**
     * @desc 生成accessToken
     * @param $params
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAccessToken($params) {
        $where = [
            ['user_secret_id', '=', $params['secretId']],
            ['user_secret_key', '=', $params['secretKey']]
        ];
        $info = App::model('User')->where($where)->find();
        if(!$info) {
            $this->errorCode = EC_API_USER_NOT_EXIST;
            return false;
        }
    
        //生成Token,设置过期时间
        $tokenExpireTime = time() + Config::get('token_expires');
        $userInfo = [
            'userId'     => $info['user_id'],
            'secretId'   => $params['secretId'],
            'secretKey'  => $params['secretKey'],
            'userName'   => $info['user_phone'] ?: $info['user_email'],
            'expireTime' => $tokenExpireTime
        ];
        $token = Jwt::encode($userInfo, Config::get('token_sign_key'));
    
        //记录到redis，用于同时超时判断
        Cache::tag('member')->set(Config::get('token_cache_key') . $userInfo['userId'] .'_expire', $tokenExpireTime);
        
        return [
            'expireTime'  => $tokenExpireTime,
            'accessToken' => $token,
        ];
    }
}
